/*
 * @lc app=leetcode.cn id=112 lang=javascript
 *
 * [112] 路径总和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
// 迭代版 深度优先遍历
// 先压栈到最左节点，再模拟程序出栈处理每个节点
// 使用prev标记 右子树完全反问，也就是处理出栈节点，
// 节点右子树为null，或者为prev，该节点就标记为右子树完全访问
// 进行深度优先遍历
 var hasPathSum = function(root, targetSum) {
   const stack = []
   let current = root
   let count = 0
   let prev = null
   while (stack.length || current) {
     while (current) {
       count += current.val
       stack.push(current)
       current = current.left
     }
     current = stack.pop()
     if (!current.left && !current.right && count === targetSum) {
      return true
     }
     if (current.right === null || current.right == prev) {
      count -= current.val
      prev = current
      current = null
     } else {
      stack.push(current)
      current = current.right
     }
   }
   return false
};
// @lc code=end

// 递归版
// 递归到叶子节点去判断是否有符合的值
var hasPathSum = function(root, targetSum) {
  const findTarget = (node, count = 0) => {
    if (!node) return false
    if (!node.left && !node.right) {
      return node.val + count === targetSum
    }
    const total = node.val + count
    return findTarget(node.left, total) || findTarget(node.right, total)
  }
  return findTarget(root)
};